package com.gaojiawei.review;

public class ReviewAdd {
    public static void main(String[] args) {

    }

    public static ListNode addTwo(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        int len1 = getLen(l1);
        int len2 = getLen(l2);
        ListNode l;
        ListNode s;
        l = len1 > len2 ? l1 : l2;
        s = l == l1 ? l2 : l1;

        ListNode curl = l;
        ListNode curs = s;
        int arange = 0;
        while (curl != null && curs != null) {
            int sum = curl.val + curs.val + arange;
            curl.val = sum % 10;
            arange = sum / 10;
            curl = curl.next;
            curs = curs.next;
        }
        while(curl != null){
            int sum = curl.val+arange;
            curl.val = sum%10;
            arange = sum/10;
            curl = curl.next;
        }
        if(arange != 0){
            curl = new ListNode(arange);
        }


        return l;


    }

    public static int getLen(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }

    public static ListNode merge(ListNode l1,ListNode l2 ){
        if(l1 == null || l2 == null){
            return l1 == null? l2:l1;
        }
        ListNode head = null;
        ListNode cur1 = null;
        ListNode cur2 = null;
        if(l1.val <= l2.val){
            head = l1;
            cur1 = l1.next;
            cur2 = l2;
        }else {
            head = l2;
            cur1 = l1;
            cur2 = l2.next;
        }
        ListNode cur = head;

        while(cur1 != null && cur2 != null){
            if(cur1.val < cur2.val){
                cur.next = cur1;
                cur1 = cur1.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
        }
        if(cur1 != null){
            cur.next = cur1;
        }else {
            cur.next = cur2;
        }

        return head;

    }

    public static ListNode reverse(ListNode head){
        if(head == null ||head.next == null){
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while(cur != null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = cur.next;
        }
        return pre;
    }


    public static class ListNode {
        ListNode next;
        int val;

        public ListNode(int val){
            this.val = val;
        }
    }
}
